import axios from "axios";
import 'dotenv/config';
import { getTenantAccessToken } from "./util/CertificateUtils";
import { FeiShuTable, getTableId } from "./util/TableUtils";
import { FSBitableQuery } from "./queryObj/ConditionalBitableQuery";

const {
    FEISHU_API_URL: feishuApi,
    FEISHU_APP_TOKEN: appToken
} = process.env;

const API = (tableId: string) => `${feishuApi}/bitable/v1/apps/${appToken}/tables/${tableId}/records`

export async function saveTableRecords(
    table: FeiShuTable,
    record: { [key: string]: any }
) {
    const tableId = getTableId(table)
    const {
        data: { msg, code, data },
    } = await axios.post(
        `${API(tableId)}`,
        { fields: record },
        {
            headers: { Authorization: `Bearer ${await getTenantAccessToken()}` },
        }
    );

    if (code != 0) throw Error(msg);
    return { id: data.record.id, ...data.record.fields };
}

export async function updateTableRecords(
    table: FeiShuTable,
    record: { [key: string]: any },
    recordId: string
) {
    const tableId = getTableId(table)
    const {
        data: { msg, code, data }
    } = await axios.put(
        `${API(tableId)}/${recordId}`,
        { fields: record },
        {
            headers: { Authorization: `Bearer ${await getTenantAccessToken()}` },
        }
    );

    if (code != 0) throw Error(msg);
    return data;
}

export async function deleteTableRecords(
    table: FeiShuTable,
    recordId: string
) {
    const tableId = getTableId(table)
    const {
        data: { msg, code, data }
    } = await axios.delete(
        `${API(tableId)}/${recordId}`,
        {
            headers: { Authorization: `Bearer ${await getTenantAccessToken()}` },
        }
    );
    return { msg, code, data };
}


/**
 * 旧版查询
 * @param table 
 * @param urlParam 
 * @param id 
 * @returns 
 */
export async function getTableRecords(
    table: FeiShuTable,
    urlParam: string,
    id?: string
) {
    const tableId = getTableId(table)

    const url = !!id ? `${API(tableId)}/${id}` : `${API(tableId)}?${urlParam}`

    const {
        data: { msg, code, data }
    } = await axios.get(
        `${url}`,
        {
            headers: { Authorization: `Bearer ${await getTenantAccessToken()}` },
        }
    );

    if (code != 0) throw Error(msg);

    const results: any[] = [];

    if (data["total"] > 0) {
        const items = data["items"];
        for (const item of items) {
            results.push({ id: item.id, ...item.fields })
        }
        return results;
    }

    if (!!id) return { id: data.record.id, ...data.record.fields }

    return null
}

/**
 * 新版查询
 * @param table 
 * @returns 
 */
export async function getTableRecordsSearch(
    table: FeiShuTable,
    queryBody: FSBitableQuery,
    urlParam: string = ''
) {
    const tableId = getTableId(table)
    const url = `${API(tableId)}/search?${urlParam}`
    const {
        data: { code, data }
    } = await axios.post(
        `${url}`, queryBody, {
        headers: {
            Authorization: `Bearer ${await getTenantAccessToken()}`
        }
    }
    );
    if (code != 0) return []

    return data;

}

/**
 * 新版查询
 * @param table 
 * @returns 
 */
export async function getTableRecordsById(
    table: FeiShuTable,
    id: string
) {
    const tableId = getTableId(table)

    const url = `${API(tableId)}/batch_get`

    const {
        data: { code, data }
    } = await axios.post(
        `${url}`,
        { record_ids: [id] },
        {
            headers: {
                Authorization: `Bearer ${await getTenantAccessToken()}`
            }
        }
    );
    if (code != 0 || data.records.length == 0) return
    return {
        id: data.records[0].record_id,
        ...data.records[0].fields
    }
}

/**
 * 新版查询
 * @param table 
 * @returns 
 */
export async function getTableRecordsBatch(
    table: FeiShuTable,
    record_ids: string[] = []
) {
    const tableId = getTableId(table)

    const url = `${API(tableId)}/batch_get`

    const {
        data: { code, data }
    } = await axios.post(
        `${url}`, { record_ids },
        {
            headers: {
                Authorization: `Bearer ${await getTenantAccessToken()}`
            }
        }
    );

    if (code != 0) return []

    const results: any[] = [];
    const items = data["records"];
    for (const item of items) {
        results.push({ id: item.record_id, ...item.fields })
    }

    return results;
}